// ============ 全局配置 ============
const API_URL = '/api/rest/dept';
let gridInstance = null;
const deptModal = new bootstrap.Modal(document.getElementById('deptModal'));
const deptForm = document.getElementById('dept-form');
const deptModalLabel = document.getElementById('deptModalLabel');
const alertMessage = document.getElementById('alertMessage');

// ============ 页面加载初始化 ============
document.addEventListener('DOMContentLoaded', () => {
  // 登录状态校验
  loginCheck();
  // 初始化父部门下拉框
  initParentDept();
  // 初始化表格
  initGrid();
  // 绑定表单提交事件
  bindFormSubmit();
  // 绑定搜索表单事件
  bindSearchForm();
  // 绑定模态框关闭事件（重置表单）
  bindModalClose();
});

// ============ Grid表格初始化 ============
function initGrid() {
  const columns = [
    { name: 'ID', id: 'id', width: '10%' },
    { name: '部门名称', id: 'name', sort: true },
    { name: '描述', id: 'remark', sort: true },
    { 
      name: '状态', 
      id: 'enableState', 
      sort: true,
      formatter: (value) => {
        const className = value === '启用' ? 'badge bg-success' : 'badge bg-warning';
        return gridjs.html(`<span class="${className}">${value}</span>`);
      }
    },
    { 
      name: '创建时间', 
      id: 'createAt', 
      sort: true,
      formatter: (value) => new Date(value).toLocaleString()
    },
    {
      name: '操作',
      id: 'actions',
      width: '20%',
      formatter: (_, row) => {
        const id = row.cells[0].data;
        const status = row.cells[3].data;
        return gridjs.html(`
          <button type="button" class="btn btn-sm btn-outline-primary m-1" onclick="openEditModal('${id}')">
            <i class="fas fa-edit"></i> 编辑
          </button>
          <button type="button" class="btn btn-sm ${status === '启用' ? 'btn-outline-warning' : 'btn-outline-success'} m-1" onclick="toggleDept('${id}')">
            <i class="fas fa-exchange-alt"></i> ${status === '启用' ? '停用' : '启用'}
          </button>
        `);
      }
    }
  ];

  const gridOptions = {
    columns,
    server: {
      url: API_URL,
      then: (data) => {
        return data.content.map(dept => [
          dept.id,
          dept.name,
          dept.remark || '-',
          dept.enableState,
          dept.createAt
        ]);
      },
      total: (data) => data.totalElements,
      loading: {
        message: '加载中...',
        html: () => gridjs.html('<div class="text-center py-4"><i class="fas fa-spinner fa-spin me-2"></i> 加载部门数据中...</div>')
      }
    },
    pagination: {
      limit: 10, // 每页10条
      server: {
        url: (prev, page, limit) => addQueryParam(prev, `page=${page - 1}&size=${limit}`) // 注意：后端分页可能从0开始
      }
    },
    search: false,
    sort: true,
    language: {
      pagination: {
        previous: '上一页',
        next: '下一页',
        showing: '显示第',
        of: '条，共',
        to: '至',
        results: '条记录'
      },
      noRecordsFound: '暂无部门数据'
    }
  };

  // 销毁旧实例，重建表格
  if (gridInstance) gridInstance.destroy();
  gridInstance = new gridjs.Grid(gridOptions).render(document.getElementById('gridjs-container'));
}

// ============ 父部门下拉框初始化 ============
function initParentDept() {
  const parentSelect = deptForm.querySelector('[name="parentId"]');
  fetch(`${API_URL}/all`)
    .then(res => {
      if (!res.ok) throw new Error('获取父部门失败');
      return res.json();
    })
    .then(depts => {
      // 清空现有选项（保留根部门）
      parentSelect.innerHTML = '<option value="#" selected>根部门</option>';
      // 添加子部门选项
      depts.forEach(dept => {
        const option = document.createElement('option');
        option.value = dept.id;
        option.textContent = dept.namePath || dept.name; // 优先显示路径
        parentSelect.appendChild(option);
      });
    })
    .catch(error => {
      showToast(error.message, 'error');
    });
}

// ============ 新增模态框 ============
function openAddModal() {
  // 重置表单
  deptForm.reset();
  deptForm.classList.remove('was-validated');
  alertMessage.innerHTML = '';
  // 启用ID输入框
  deptForm.querySelector('[name="id"]').disabled = false;
  // 设置模态框标题
  deptModalLabel.textContent = '新增部门';
  // 打开模态框
  deptModal.show();
}

// ============ 编辑模态框 ============
function openEditModal(id) {
  // 重置表单状态
  deptForm.reset();
  deptForm.classList.remove('was-validated');
  alertMessage.innerHTML = '';
  // 禁用ID输入框（不可修改）
  deptForm.querySelector('[name="id"]').disabled = true;
  // 设置模态框标题
  deptModalLabel.textContent = '编辑部门';

  // 获取部门详情
  fetch(`${API_URL}/${id}`)
    .then(res => {
      if (!res.ok) throw new Error('获取部门详情失败');
      return res.json();
    })
    .then(dept => {
      // 填充表单
      Object.keys(dept).forEach(key => {
        const field = deptForm.querySelector(`[name="${key}"]`);
        if (field) field.value = dept[key] || '';
      });
      // 打开模态框
      deptModal.show();
    })
    .catch(error => {
      showToast(error.message, 'error');
    });
}

// ============ 表单提交（新增/编辑） ============
function bindFormSubmit() {
  deptForm.addEventListener('submit', (e) => {
    e.preventDefault();
    // 表单验证
    if (!deptForm.checkValidity()) {
      deptForm.classList.add('was-validated');
      return;
    }

    const isEdit = deptForm.querySelector('[name="id"]').disabled;
    const id = deptForm.querySelector('[name="id"]').value;
    const formData = formToJson(deptForm);
    const config = {
      method: isEdit ? 'PATCH' : 'POST',
      headers: { 'Content-Type': 'application/json' },
      body: JSON.stringify(formData)
    };

    // 编辑时使用带ID的URL
    const url = isEdit ? `${API_URL}/${id}` : API_URL;

    fetch(url, config)
      .then(res => {
        if (!res.ok) {
          return res.json().then(err => {
            throw new Error(err.message || (isEdit ? '编辑部门失败' : '新增部门失败'));
          });
        }
        return res.json();
      })
      .then(() => {
        // 操作成功
        deptModal.hide();
        showToast(isEdit ? '编辑部门成功' : '新增部门成功');
        initGrid(); // 刷新表格
      })
      .catch(error => {
        // 显示错误信息
        alertMessage.innerHTML = `<div class="alert alert-danger">${error.message}</div>`;
        showToast(error.message, 'error');
      });
  });
}

// ============ 启用/停用部门 ============
function toggleDept(id) {
  fetch(`${API_URL}/${id}/toggle`, { method: 'PATCH' })
    .then(res => {
      if (!res.ok) {
        return res.json().then(err => {
          throw new Error(err.message || '状态切换失败');
        });
      }
      return res.json();
    })
    .then(() => {
      showToast('部门状态切换成功');
      gridInstance.forceRender(); // 刷新表格
    })
    .catch(error => {
      showToast(error.message, 'error');
    });
}

// ============ 搜索表单绑定 ============
function bindSearchForm() {
  const searchForm = document.getElementById('search-form');
  searchForm.addEventListener('submit', (e) => {
    e.preventDefault();
    const formData = new FormData(searchForm);
    const params = new URLSearchParams(formData).toString();
    // 更新表格请求URL
    gridInstance.updateConfig({
      server: {
        ...gridInstance.config.server,
        url: addQueryParam(API_URL, params)
      }
    }).forceRender();
  });

  // 重置按钮
  searchForm.querySelector('[type="reset"]').addEventListener('click', () => {
    setTimeout(() => {
      gridInstance.updateConfig({
        server: { ...gridInstance.config.server, url: API_URL }
      }).forceRender();
    }, 100);
  });
}

// ============ 模态框关闭事件（重置表单） ============
function bindModalClose() {
  document.getElementById('deptModal').addEventListener('hidden.bs.modal', () => {
    deptForm.reset();
    deptForm.classList.remove('was-validated');
    alertMessage.innerHTML = '';
  });
}

// ============ 暴露全局函数 ============
window.initGrid = initGrid;
window.openAddModal = openAddModal;
window.openEditModal = openEditModal;
window.toggleDept = toggleDept;